package top.chenyaohua.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import top.chenyaohua.asm.BeanMetadata;
import top.chenyaohua.beans.MapperBean;
import top.chenyaohua.context.BeanFactory;
import top.chenyaohua.driver.ConnectionPool;
import top.chenyaohua.utils.InitExecutionUtils;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;
import java.util.Map;

public class JdbcProxy implements MethodInterceptor {



    public  <T> T getInstall(Class<?> cals){
        Enhancer enhancer = new Enhancer();
        enhancer.setCallback(this);
        enhancer.setSuperclass(cals);
        return (T) enhancer.create();
    }

    @Override
    public Object intercept (Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        String name = method.getName();
        List<MapperBean> mapper = InitExecutionUtils.getMapper();
        List<BeanMetadata> beanMetadata = BeanFactory.getBeanMetadata();

        for (MapperBean mp : mapper) {
            if (mp.getNamespace().equals(method.getDeclaringClass().getName())){
                Map<String, Map<String, String>> params = mp.getParams();
                Map<String, String> aps = params.get(name);
                String tagName = aps.get("type");
                switch (tagName){
                    case "select":
                            //jdbc 查询
                        String sql = aps.get("sql");
                        String typeCla = aps.get("resultType");

                        Object o2 = Class.forName(typeCla).newInstance();

                        ConnectionPool connectionPool = ConnectionPool.newInstall();
                        Connection connection = connectionPool.getConnection();
                        Statement statement = connection.createStatement();
                        ResultSet resultSet = statement.executeQuery(sql);

                        while (resultSet.next()) {


                        }
                        return o2;
                    case "update":

                        return null;
                    case "delete":

                        return null;
                    case "insert":

                        return null;
                    default:
                        throw new RuntimeException("");
                }

            }

        }

        return null;

    }
}
